<?php
declare (strict_types=1);

namespace app\platform\controller;

use think\facade\View;
use think\response\Json;

class Merchant extends PlatformBase
{
    public function index(): string
    {
        $merchantBusiness = new \app\platform\business\Enterprise();
        $enterprises      = $merchantBusiness->getAllEnterprise();

        $rows    = [];
        $rows[0] = ['id' => 0, 'title' => '全部', 'children' => [], 'spread' => true];
        foreach ($enterprises as $key => $enterprise) {
            $rows[0]['children'][] = ['id' => $enterprise['id'], 'title' => $enterprise['name'], 'children' => [], 'pid' => 0];
        }
        View::assign(['enterprises' => json_encode($rows, JSON_UNESCAPED_UNICODE)]);

        return View::fetch();
    }

    public function lists(): string
    {
        $enterpriseId = $this->request->param('enterprise_id', 0, 'intval');
        View::assign(['enterprise_id' => $enterpriseId]);
        return View::fetch();
    }

    public function list(): Json
    {
        $page         = $this->request->param('page', 1, 'intval');
        $limit        = $this->request->param('limit', 10, 'intval');
        $username     = $this->request->param('$username', '', 'trim');
        $status       = $this->request->param('status', 0, 'intval');
        $enterpriseId = $this->request->param('enterprise_id', 0, 'intval');

        $where = [];
        if ($username) {
            $where[] = ['name', 'like', '%' . $username . '%'];
        }
        if ($status) {
            $where[] = ['status', '=', $status];
        }
        if ($enterpriseId) {
            $where[] = ['enterprise_id', '=', $enterpriseId];
        }

        $merchantBusiness = new \app\platform\business\Merchant();
        $merchantInfo     = $merchantBusiness->getMerchantList($page, $limit, $where);
        return showList(config(self::_CONFIG_STATUS_SUCCESS_CODE), 'success', $merchantInfo['rows'], $merchantInfo['count']);
    }

    public function add(): string
    {
        $enterpriseBusiness = new \app\platform\business\Enterprise();
        $enterprises        = $enterpriseBusiness->getAllEnterprise(["status" => self::_IS_ENABLE_STATUS]);

        $roleBusiness = new \app\platform\business\Role();
        $roles        = $roleBusiness->getAllRole(["status" => self::_IS_ENABLE_STATUS]);

        View::assign(['enterprises' => $enterprises, 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE)]);
        return View::fetch();
    }

    public function doAdd(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $username        = $this->request->param('username', '', 'trim');
        $cellphone       = $this->request->param('cellphone', 0, 'trim');
        $email           = $this->request->param('email', 0, 'trim');
        $password        = $this->request->param('password', 0, 'trim');
        $confirmPassword = $this->request->param('confirm_password', 0, 'trim');
        $enterpriseId    = $this->request->param('enterprise_id', 0, 'intval');
        $status          = $this->request->param('status', 0, 'intval');
        $roleIds         = $this->request->param('role_ids', '', 'trim');

        $data     = [
            'username'         => $username,
            'cellphone'        => $cellphone,
            'email'            => $email,
            'password'         => $password,
            'confirm_password' => $confirmPassword,
            'enterprise_id'    => $enterpriseId,
            'status'           => $status == self::_IS_ENABLE_STATUS ? self::_IS_ENABLE_STATUS : self::_IS_DISABLE_STATUS,
        ];
        $validate = (new \app\platform\validate\Merchant())->scene('add');
        if (!$validate->check($data)) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), $validate->getError());
        }

        $merchantBusiness = new \app\platform\business\Merchant();
        $res              = $merchantBusiness->addMerchant($data, $roleIds);
        if ($res[self::_RESULT]) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), $res[self::_MESSAGE]);
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), $res[self::_MESSAGE]);
    }

    public function edit(): string
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            View::assign(['msg' => self::_PARAMETER_ERROR_MESSAGE]);
            return View::fetch('permission/msg');
        }

        $merchantBusiness = new \app\platform\business\Merchant();
        $merchant         = $merchantBusiness->findMerchantById($id);
        if (empty($merchant)) {
            View::assign(['msg' => self::_PARAMETER_ERROR_MESSAGE]);
            return View::fetch('permission/msg');
        }

        $enterpriseBusiness = new \app\platform\business\Enterprise();
        $enterprises        = $enterpriseBusiness->getAllEnterprise(["status" => self::_IS_ENABLE_STATUS]);

        $roleBusiness = new \app\platform\business\Role();
        $roles        = $roleBusiness->getAllRole(["status" => self::_IS_ENABLE_STATUS]);

        View::assign(["merchant" => $merchant, 'enterprises' => $enterprises, 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE)]);

        return View::fetch();
    }

    public function doEdit(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $id              = $this->request->param('id', 0, 'intval');
        $username        = $this->request->param('username', '', 'trim');
        $cellphone       = $this->request->param('cellphone', 0, 'trim');
        $email           = $this->request->param('email', 0, 'trim');
        $password        = $this->request->param('password', 0, 'trim');
        $confirmPassword = $this->request->param('confirm_password', 0, 'trim');
        $enterpriseId    = $this->request->param('enterprise_id', 0, 'intval');
        $status          = $this->request->param('status', 0, 'intval');
        $roleIds         = $this->request->param('role_ids', '', 'trim');

        $data = [
            'id'               => $id,
            'username'         => $username,
            'cellphone'        => $cellphone,
            'email'            => $email,
            'password'         => $password,
            'confirm_password' => $confirmPassword,
            'enterprise_id'    => $enterpriseId,
            'status'           => $status == self::_IS_ENABLE_STATUS ? self::_IS_ENABLE_STATUS : self::_IS_DISABLE_STATUS,
        ];

        // 不输入密码，则不修改密码
        if (empty($password) && empty($confirmPassword)) {
            unset($data['password']);
            unset($data['confirm_password']);
        } else if ($data['password'] != $data['confirm_password']) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), '两次密码不一致');
        }

        $validate = (new \app\platform\validate\Merchant())->scene('edit');
        if (!$validate->check($data)) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), $validate->getError());
        }

        $merchantBusiness = new \app\platform\business\Merchant();
        $res              = $merchantBusiness->updateMerchant($id, $data, $roleIds);
        if ($res[self::_RESULT]) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), $res[self::_MESSAGE]);
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), $res[self::_MESSAGE]);
    }


    public function doDelete(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_PARAMETER_ERROR_MESSAGE);
        }

        $merchantBusiness = new \app\platform\business\Merchant();
        $res              = $merchantBusiness->deleteMerchant($id);
        if ($res[self::_RESULT]) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), $res[self::_MESSAGE]);
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), $res[self::_MESSAGE]);
    }

    public function pwd(): string
    {
        $merchantBusiness = new \app\platform\business\Merchant();
        $merchant         = $merchantBusiness->getMerchantUserFromSession();
        View::assign(['merchant' => $merchant]);
        return View::fetch();
    }

    public function doPwd():Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $merchantBusiness = new \app\platform\business\Merchant();
        $merchant         = $merchantBusiness->getMerchantUserFromSession();

        $id              = $merchant['id'];
        $password        = $this->request->param('password', 0, 'trim');
        $confirmPassword = $this->request->param('confirm_password', 0, 'trim');
        $data            = [
            'id'               => $id,
            'password'         => $password,
            'confirm_password' => $confirmPassword,

        ];

        if ($data['password'] != $data['confirm_password']) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), '两次密码不一致');
        }

        $validate = (new \app\platform\validate\Merchant())->scene('pwd');
        if (!$validate->check($data)) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), $validate->getError());
        }

        $merchantBusiness = new \app\platform\business\Merchant();
        $res              = $merchantBusiness->updateMerchant($id, $data);
        if ($res[self::_RESULT]) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), $res[self::_MESSAGE]);
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), $res[self::_MESSAGE]);
    }
}
